angular.module('memydataservices', [])

  .factory('MeMyData', function ($resource, $rootScope, $cordovaImagePicker, $cordovaCamera, ENV, Storage,Toast,Loading) {

    //设置访问接口路径
    var APIUrl = ENV.api;

    //访问获取用户信息的接口
    var toMeInfoResource = $resource(APIUrl + "meInfo/toMeInfo.do");
    var updateMeInfoResource = $resource(APIUrl + "meInfo/updateMeInfo.do");
    var identifyResource = $resource(APIUrl + "me/addIdentify.do");

    var imgUploadPath = APIUrl + 'servlet/imageUploadServlet';


    var meInfoJson;
    var identityMsgJson;
    var infoUpdateJson;
    var uploadAvatarJson;


    return {
      //获取“我的”个人资料
      getMeInfo: function (memberId) {
        toMeInfoResource.save(
          {member_id: memberId},
          function (data) {
            //这里为回调函数，data为服务器返回的值
            meInfoJson = data;
            console.log('接口传来的数据' + data);
            $rootScope.$broadcast('Me.meInfo');
          }
        );
      },

      //返回“我的”个人资料
      getMeInfoJson: function () {
        return meInfoJson;
      },

      //发送认证消息
      sendIdentifyMsgById: function (memberId) {
        identifyResource.save(
          {member_id: memberId},
          function (data) {
            //data为服务器返回的处理结果，true为状态更新成功，false为更新失败
            identityMsgJson = data;
            $rootScope.$broadcast('Me.mydataIdentifyGot');
          }
        );
      },

      //返回认证消息
      getIdentityMsgJson: function () {
        return identityMsgJson;
      },

      saveMemberInfo: function (id, username, gender, birthday, hobby, contact, email, address, job, img_url) {
        updateMeInfoResource.save(
          {
            member_id: id,
            member_name: username,
            member_gender: gender,
            member_birthday: birthday,
            member_job: job,
            member_hobby: hobby,
            member_contact: contact,
            member_email: email,
            member_address: address,
            member_img_url: img_url
          },
          function (data) {
            infoUpdateJson = data;
            $rootScope.$broadcast('Me.memberInfoUpdated');
          }
        );
      },

      getInfoUpdateJson: function () {
        return infoUpdateJson;
      },


      //拍照、本地获取图片，并且上传文件功能
      takePictureByIndex: function (index, memberId) {

        var pictureSource;
        var destinationType;

        //检测是否为真机设备
        document.addEventListener("deviceready", onDeviceReady, false);
        //如果是真机设备，则初始化
        function onDeviceReady() {
          pictureSource = navigator.camera.PictureSourceType;//图片来源，相机或图库
          destinationType = navigator.camera.DestinationType;//定义类型
        }

        //图片上传成功时调用
        var win = function (r) {
          Loading.hideLoading();
          Toast.showMessage("上传成功");
          uploadAvatarJson = r.response;
          $rootScope.$broadcast('Me.uploadAvatar');
        };

        //图片上传失败时调用
        var fail = function (error) {
          Loading.hideLoading();
          Toast.showMessage("上传失败,请稍后再试");
        };

        //若Uri数据类型成功时，调用该方法上传文件
        function onPhotoURISuccess(imageURI) {
          Loading.showLoading();
          //imageURI数据直接返回到界面，可以获取到图片
          var options = new FileUploadOptions();
          options.fileKey = "file";
          options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
          options.mimeType = "image/jpeg";
          //可以携带参数上传
          var params = {};
          params['member_id'] = memberId;
          options.params = params;
          var ft = new FileTransfer();
          //上传头像
          ft.upload(imageURI, encodeURI(imgUploadPath), win, fail, options);
        }

        if (index == 0) {
          //调用拍照功能，加上编辑功能
          var options1 = {
            quality: 30,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            allowEdit: true,
            encodingType: Camera.EncodingType.JPEG,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: false,
            correctOrientation: true
          };

          $cordovaCamera.getPicture(options1).then(
            function (imageData) {
              //拍照成功时调用
              onPhotoURISuccess(imageData);
            },
            function (err) {
              //拍照失败时调用,do something
            });

        }
        else if (index == 1) {
          //调用获取本地图片功能
          var options = {
            maximumImagesCount: 1,
            quality: 20
          };

          $cordovaImagePicker.getPictures(options)
            .then(function (results) {
              //results为获取的图片集合
              for (var i = 0; i < results.length; i++) {
                onPhotoURISuccess(results[i]);
              }
            });
        }
      },

      //获取修改的头像路径
      getUploadAvatarJson: function () {
        return uploadAvatarJson;
      }

    }


  });
